﻿using ProjectScheduling_web.model;
using SqlSugar;

namespace ProjectScheduling_web.dao
{
    public class ReceiveMoney_ContractDao : BaseDao<ReceiveMoney_Contract>
    {
        public static readonly ReceiveMoney_ContractDao Base = new();
        public PageData<ReceiveMoney_Contract> Check_Contract_Datas(int page, int row, string key,List<int> noids)
        {
            int total = 0;
            var data =
                Db.Queryable<Contract>()
                .WhereIF(!string.IsNullOrEmpty(key), it => (it.Code != null && it.Code.Contains(key)) || (it.ProjectName != null && it.ProjectName.Contains(key)))
                .WhereIF(noids.Count>0, it => !noids.Contains(it.Id))
                .Select(it => new ReceiveMoney_Contract
                {
                    ContractCode = it.Code,
                    ContractId = it.Id,
                    LeastMoney = it.Money,
                    Money = 0,
                    Note = "",
                    ProjectName = it.ProjectName,
                }).ToPageList(page, row, ref total);
            var ids = data.Select(it => it.ContractId).ToList();
            var totals = Db.Queryable<ReceiveMoney_Contract>().Where(it => ids.Contains(it.ContractId)).GroupBy(it => it.ContractId).Select(it => new { it.ContractId, Money = SqlFunc.AggregateSum(it.Money) }).ToList();
            data.ForEach(item =>
            {
                var obj = totals.FirstOrDefault(it => it.ContractId == item.ContractId);
                if (obj != null)
                {
                    item.LeastMoney -= obj.Money;
                }
            });
            return new()
            {
                Items = data,
                Total = total
            };
        }
    }
}
